package com.athuahua.spzx.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.athuahua.spzx.entity.PaymentInfo;
import com.athuahua.spzx.exception.CodeException;
import com.athuahua.spzx.properties.AlipayProperties;
import com.athuahua.spzx.service.AliPayService;
import com.athuahua.spzx.service.PaymentInfoService;
import com.athuahua.spzx.utils.ResultCodeEnum;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;

/**
 * @Author: huahua
 * @Date: 2024/8/26 0026
 * @Time: 14:01
 * @Description:
 */
@Service
public class AliPayServiceImpl implements AliPayService {
    /**
     * 支付宝下单
     * 1. 根据订单编号获得订单信息，保存支付记录
     * 2. 调用支付宝接口，生成支付链接
     * 2.1 构建参数
     * 3. 返回支付链接
     */
    @Resource
    private PaymentInfoService paymentInfoService;

    @Resource
    private AlipayProperties alipayProperties;

    @Resource
    private AlipayClient alipayClient;


    @Override
    public String submitAlipay(String orderNo) {
        //1. 根据订单编号获得订单信息，保存支付记录
        PaymentInfo paymentInfo = paymentInfoService.savePaymentInfo(orderNo);
        //2.1 构建参数
        AlipayTradeWapPayRequest alipayRequest = buildAlipayRequest(paymentInfo);
        //2 调用支付宝接口，生成支付链接
        try {
            AlipayTradeWapPayResponse response = alipayClient.pageExecute(alipayRequest);
            if(response.isSuccess()){
                // 支付成功
                return response.getBody();
            } else{
                // 支付失败
                throw new CodeException(ResultCodeEnum.DATA_ERROR);
            }

        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }


    }

    private AlipayTradeWapPayRequest buildAlipayRequest(PaymentInfo paymentInfo) {
        //创建API对应的request
        AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();

        // 同步回调
        alipayRequest.setReturnUrl(alipayProperties.getReturnPaymentUrl());

        // 异步回调
        alipayRequest.setNotifyUrl(alipayProperties.getNotifyPaymentUrl());

        // 准备请求参数 ，声明一个map 集合
        HashMap<String, Object> map = new HashMap<>();
        map.put("out_trade_no",paymentInfo.getOrderNo());
        map.put("product_code","QUICK_WAP_WAY");
        //map.put("total_amount",paymentInfo.getAmount());
        map.put("total_amount",new BigDecimal("0.01")); //测试用金额
        map.put("subject",paymentInfo.getContent());
        alipayRequest.setBizContent(JSON.toJSONString(map));

        return alipayRequest;
    }
}
